﻿#region << 文 件 说 明 >>
/*----------------------------------------------------------------
// 文件名称：BaseSingleton
// 创 建 者：杨程
// 创建时间：2021/4/26 11:43:25
// 文件版本：V1.0.0
// ===============================================================
// 功能描述：
//		
//
//----------------------------------------------------------------*/
#endregion




namespace Vampirewal.Core;

/// <summary>
/// 所有使用单例模式的基类，需要被继承
/// </summary>
/// <typeparam name="T">填写类的名称</typeparam>
public class BaseSingleton<T> : ObservableObject where T : BaseSingleton<T>
{
    private volatile static T _instance;
    private static readonly object _objLock = new object();

    /// <summary>
    /// 获取单例实例
    /// </summary>
    public static T Instance
    {
        get
        {
            if (_instance == null)
            {
                lock (_objLock)
                {
                    if (_instance == null)
                    {
                        _instance = CreateInstance();
                        _instance.Init();//保证只调用一次
                    }
                }
            }
            return _instance;
        }
    }

    /// <summary>
    /// 初始化
    /// </summary>
    protected virtual void Init()
    {

    }

    private static T CreateInstance()
    {
        //return (T)typeof(T).GetConstructor(
        //    BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,
        //    null, 
        //    Type.EmptyTypes,
        //    null)
        //    ?.Invoke(null);

        return Activator.CreateInstance(typeof(T),true) as T;
    }


    /// <summary>
    /// 获取单例实例
    /// </summary>
    /// <returns></returns>
    public static T GetInstance() => Instance;
}
